package com.hmdp.utils;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
public class RedisIdWorker {

    /**
     * 开始时间戳2000-01-01 00:00:00
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    // 序列号位数
    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix) {
        //1、生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);//获取当前时间戳
        long timestamp = nowSecond - BEGIN_TIMESTAMP;//获取时间戳 相减的秒数

        //2、生成序列号
        //获取当前日期精确到天--1方便日后统计数据。2防止key达到上限
        String date = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);


        //3、拼接返回
        return timestamp << COUNT_BITS | count;//timestamp左移32位，让位给 count，用或运算拼接，0 1得1，0 0得0，保证得原数据不变
    }
}
